<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" class="custom-dialog" width="80%">
    <div class="form-container">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        :label-width="labelWidth"
        v-loading="formLoading"
        class="custom-form"
      >
        <el-form-item
          label="广告账户"
          prop="accountId"
          v-if="formType == 'create'"
          class="form-item"
        >
          <el-select
            v-model="formData.accountId"
            placeholder="请选择广告账户"
            @change="getAdvertiserList"
            class="custom-select"
          >
            <el-option
              v-for="item in accountSimpleList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="已授权广告账户"
          prop="advertiserList"
          v-if="formType == 'create'"
          class="form-item"
        >
          <div class="table-wrapper">
            <el-table
              :data="filterTableData"
              border
              ref="tableRef"
              @selection-change="handleSelectionChange"
              :max-height="tableMaxHeight"
              row-key="id"
              default-expand-all
              class="custom-table"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column
                prop="advertiserId"
                label="账户ID"
                :min-width="100"
              ></el-table-column>
              <el-table-column
                prop="advertiserName"
                label="账户名称"
                :min-width="150"
              ></el-table-column>
              <el-table-column align="right" :min-width="120">
                <template #header>
                  <el-input
                    v-model="search"
                    size="small"
                    placeholder="查找账号名称"
                    class="search-input"
                    clearable
                  >
                    <template #prefix>
                      <Icon icon="ep:search" class="search-icon" />
                    </template>
                  </el-input>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>

        <el-form-item label="状态" prop="status" class="form-item">
          <el-radio-group v-model="formData.status" class="custom-radio-group">
            <el-radio :label="1" class="custom-radio">启用</el-radio>
            <el-radio :label="0" class="custom-radio">不启用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="执行间隔(分钟)" prop="minInterval" class="form-item">
          <el-input-number
            v-model="formData.minInterval"
            placeholder="请输入执行间隔"
            :min="1"
            :max="100"
            class="custom-input-number"
          />
        </el-form-item>

        <el-form-item label="转入位置" prop="transPos" class="form-item">
          <el-radio-group v-model="formData.transPos" class="custom-radio-group">
            <el-radio :label="1" class="custom-radio">线索列表</el-radio>
            <el-radio :label="2" class="custom-radio">线索公海</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="过滤选项" class="form-item switch-group">
          <div class="switch-item">
            <span class="switch-label">名称为空时过滤:</span>
            <el-switch
              v-model="formData.filterEmptyName"
              :inactive-value="0"
              :active-value="1"
              class="custom-switch"
              style="--el-switch-on-color: #0052cc; --el-switch-off-color: #dcdfe6"
            />
          </div>
          <div class="switch-item">
            <span class="switch-label">电话为空时过滤:</span>
            <el-switch
              v-model="formData.filterEmptyMobile"
              :inactive-value="0"
              :active-value="1"
              class="custom-switch"
              style="--el-switch-on-color: #0052cc; --el-switch-off-color: #dcdfe6"
            />
          </div>
        </el-form-item>

        <el-form-item label="去重选项" class="form-item switch-group">
          <div class="switch-item">
            <span class="switch-label">电话重复时过滤:</span>
            <el-switch
              v-model="formData.filterRepeatMobile"
              :inactive-value="0"
              :active-value="1"
              class="custom-switch"
              style="--el-switch-on-color: #0052cc; --el-switch-off-color: #dcdfe6"
            />
          </div>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="submitForm" type="primary" :disabled="formLoading" class="submit-btn">
          确 定
        </el-button>
        <el-button @click="dialogVisible = false" class="cancel-btn">取 消</el-button>
      </div>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import * as ClueTransRuleApi from '@/api/crm/cluetransrule'
import * as AdAccountApi from '@/api/ad/account'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  accountId: undefined,
  status: undefined,
  minInterval: undefined,
  transPos: undefined,
  advertiserList: undefined,
  filterEmptyName: 0,
  filterEmptyMobile: 0,
  filterRepeatMobile: 0
})
const formRules = reactive({
  accountId: [
    {
      required: true,
      message: '账户ID不能为空',
      trigger: 'blur'
    }
  ],
  status: [
    {
      required: true,
      message: '状态不能为空',
      trigger: 'blur'
    }
  ],
  minInterval: [
    {
      required: true,
      message: '执行间隔不能为空',
      trigger: 'blur'
    }
  ],
  transPos: [
    {
      required: true,
      message: '转入位置不能为空',
      trigger: 'blur'
    }
  ]
})
const formRef = ref() // 表单 Ref
const accountSimpleList = ref([]) // 广告账户列表

// 响应式计算属性
const labelWidth = computed(() => {
  return window.innerWidth <= 768 ? '100px' : '140px'
})

const tableMaxHeight = computed(() => {
  return window.innerWidth <= 768 ? 250 : 300
})

/** 打开弹窗 */
const open = async (type: string, id?: number, accountList, ModuleId) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  accountSimpleList.value = accountList
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ClueTransRuleApi.getClueTransRule(id)
      // formData.value.filterEmptyMobile = formData.value.filterEmptyMobile == 0 ? false : true
      // formData.value.filterEmptyName = formData.value.filterEmptyName == 0 ? false : true
    } finally {
      formLoading.value = false
    }
  }
  if (ModuleId) {
    formData.value.moduleId = ModuleId
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return

  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    data.filterEmptyMobile = data.filterEmptyMobile ? 1 : 0
    data.filterEmptyName = data.filterEmptyName ? 1 : 0
    if (formType.value === 'create') {
      // 校验是否选择了授权账户
      if (!formData.value.advertiserList || formData.value.advertiserList.length == 0) {
        message.error('请选择授权的广告账户')
        return
      }
      await ClueTransRuleApi.createClueTransRule(data)
      message.success(t('common.createSuccess'))
    } else {
      await ClueTransRuleApi.updateClueTransRule(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    accountId: undefined,
    status: undefined,
    minInterval: undefined,
    transPos: undefined,
    advertiserList: undefined,
    filterEmptyName: 0,
    filterEmptyMobile: 0,
    filterRepeatMobile: 0
  }
  formRef.value?.resetFields()
}

// 授权的广告账户
const advertiserList = ref([])
// 获取授权的广告账户列表
const getAdvertiserList = async (accountId) => {
  const data = await AdAccountApi.getAdvertiserTreeList({
    accountId: accountId
  })
  advertiserList.value = data
}

const search = ref('')
const filterTableData = computed(() => {
  if (!search.value) {
    return advertiserList.value
  } else {
    return test(advertiserList.value, search.value)
  }
})
const test = (arr, value) => {
  // 一级查找，有符合的元素
  //   查找子级
  //       子级有    返回一级和符合的子级
  //       子级没有  返回一级
  // 一级查找，没有符合的元素
  //   查找子级
  //       子级有     返回一级 以及 符合的子级
  //       子级没有   返回空
  const res = []
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].advertiserName.includes(value)) {
      // true 父级有
      if (arr[i].children.length > 0) {
        // 子级有数据
        let childrenArr = []
        childrenArr = arr[i].children.filter((cd) => {
          return cd.advertiserName.includes(search.value)
        })
        if (childrenArr.length > 0) {
          // 子级是否有  // > 0 子级有
          res.push({
            ...arr[i],
            children: childrenArr
          })
        } else {
          // 子级没有
          res.push({
            ...arr[i],
            children: []
          })
        }
      } else {
        res.push({
          ...arr[i],
          children: []
        })
      }
    } else {
      // 父级没有
      if (arr[i].children.length > 0) {
        // 子级有数据
        let childrenArr = []
        childrenArr = arr[i].children.filter((cd) => {
          return cd.advertiserName.includes(search.value)
        })
        if (childrenArr.length > 0) {
          //子级有
          res.push({
            ...arr[i],
            children: childrenArr
          })
        }
      }
    }
  }
  return res
}

const multipleSelection = ref([])
// 已选的账户集合
const handleSelectionChange = (val) => {
  multipleSelection.value = val
  formData.value.advertiserList = val.map((v) => v.id)
}
</script>

<style scoped>
/* 对话框样式 */
.custom-dialog :deep(.el-dialog) {
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
}

.custom-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #0052cc 0%, #003d99 100%);
  color: white;
  padding: 20px 24px;
  border-radius: 12px 12px 0 0;
}

.custom-dialog :deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
  font-size: 16px;
}

.custom-dialog :deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
  font-size: 18px;
}

.custom-dialog :deep(.el-dialog__headerbtn .el-dialog__close:hover) {
  color: #f0f7ff;
}

.custom-dialog :deep(.el-dialog__body) {
  padding: 24px;
  background: #fafbfc;
}

/* 表单容器 */
.form-container {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.custom-form {
  margin: 0;
}

.form-item {
  margin-bottom: 20px;
}

.form-item :deep(.el-form-item__label) {
  color: #303133;
  font-weight: 600;
  line-height: 1.5;
}

/* 选择器样式 */
.custom-select {
  width: 50%;
  min-width: 200px;
}

.custom-select :deep(.el-input__wrapper.is-focus) {
  border-color: #0052cc;
  box-shadow: 0 0 0 1px #0052cc inset;
}

/* 表格样式 */
.table-wrapper {
  border-radius: 6px;
  overflow: hidden;
  border: 1px solid #e4e7ed;
}

.custom-table {
  border-radius: 6px;
}

.custom-table :deep(.el-table__header) {
  background: #f5f7fa;
}

.custom-table :deep(.el-table__header th) {
  background: #f5f7fa;
  border-bottom: 2px solid #0052cc;
  color: #303133;
  font-weight: 600;
  padding: 12px 0;
}

.custom-table :deep(.el-table__body tr:hover > td) {
  background-color: #f0f7ff;
}

.custom-table :deep(.el-table__body td) {
  padding: 10px 0;
}

.search-input {
  width: 100%;
}

.search-input :deep(.el-input__wrapper.is-focus) {
  border-color: #0052cc;
  box-shadow: 0 0 0 1px #0052cc inset;
}

.search-icon {
  color: #909399;
}

/* 单选框组样式 */
.custom-radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.custom-radio {
  margin-right: 0;
  padding: 8px 16px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  transition: all 0.3s ease;
  background: white;
}

.custom-radio:hover {
  border-color: #0052cc;
  background: #f0f7ff;
}

.custom-radio :deep(.el-radio__input.is-checked .el-radio__inner) {
  background-color: #0052cc;
  border-color: #0052cc;
}

.custom-radio :deep(.el-radio__input.is-checked + .el-radio__label) {
  color: #0052cc;
  font-weight: 600;
}

.custom-radio.is-checked {
  border-color: #0052cc;
  background: #f0f7ff;
}

/* 数字输入框样式 */
.custom-input-number {
  width: 50%;
  min-width: 200px;
}

.custom-input-number :deep(.el-input__wrapper.is-focus) {
  border-color: #0052cc;
  box-shadow: 0 0 0 1px #0052cc inset;
}

.custom-input-number :deep(.el-input-number__decrease),
.custom-input-number :deep(.el-input-number__increase) {
  color: #0052cc;
}

.custom-input-number :deep(.el-input-number__decrease:hover),
.custom-input-number :deep(.el-input-number__increase:hover) {
  background: #f0f7ff;
  color: #003d99;
}

/* 开关组样式 */
.switch-group {
  margin-bottom: 24px;
}

.switch-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.switch-item:hover {
  border-color: #0052cc;
  background: #f0f7ff;
}

.switch-item:last-child {
  margin-bottom: 0;
}

.switch-label {
  color: #606266;
  font-weight: 500;
  flex: 1;
}

.custom-switch {
  --el-switch-on-color: #0052cc;
  --el-switch-off-color: #dcdfe6;
}

/* 对话框底部 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 24px;
  background: #fafbfc;
  border-radius: 0 0 12px 12px;
  border-top: 1px solid #e4e7ed;
}

.submit-btn {
  padding: 8px 20px;
  border-radius: 6px;
  background: #0052cc;
  border-color: #0052cc;
  font-weight: 600;
  transition: all 0.3s ease;
}

.submit-btn:hover {
  background: #003d99;
  border-color: #003d99;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 82, 204, 0.3);
}

.submit-btn:active {
  transform: translateY(0);
}

.cancel-btn {
  padding: 8px 20px;
  border-radius: 6px;
  background: #f5f7fa;
  border-color: #dcdfe6;
  color: #606266;
  font-weight: 500;
  transition: all 0.3s ease;
}

.cancel-btn:hover {
  background: #ecf5ff;
  border-color: #0052cc;
  color: #0052cc;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .custom-dialog :deep(.el-dialog) {
    width: 95% !important;
    margin: 5vh auto;
  }

  .custom-dialog :deep(.el-dialog__header) {
    padding: 16px 20px;
  }

  .custom-dialog :deep(.el-dialog__body) {
    padding: 16px;
  }

  .form-container {
    padding: 16px;
  }

  .form-item {
    margin-bottom: 16px;
  }

  .custom-select,
  .custom-input-number {
    width: 100%;
    min-width: auto;
  }

  .custom-radio-group {
    flex-direction: column;
    gap: 8px;
  }

  .custom-radio {
    width: 100%;
    text-align: center;
  }

  .switch-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .dialog-footer {
    padding: 12px 16px;
    flex-direction: column;
  }

  .submit-btn,
  .cancel-btn {
    width: 100%;
  }

  .table-wrapper {
    overflow-x: auto;
  }

  .custom-table {
    min-width: 500px;
  }
}

@media (max-width: 480px) {
  .custom-dialog :deep(.el-dialog) {
    width: 98% !important;
    margin: 2vh auto;
  }

  .custom-dialog :deep(.el-dialog__header) {
    padding: 12px 16px;
  }

  .custom-dialog :deep(.el-dialog__title) {
    font-size: 14px;
  }

  .form-container {
    padding: 12px;
  }

  .custom-table {
    min-width: 600px;
  }
}

/* 加载状态优化 */
.el-loading-mask {
  background-color: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(2px);
}

/* 滚动条美化 */
.table-wrapper::-webkit-scrollbar {
  height: 6px;
  width: 6px;
}

.table-wrapper::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.table-wrapper::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.table-wrapper::-webkit-scrollbar-thumb:hover {
  background: #0052cc;
}

/* 动画效果 */
.form-container {
  transition: all 0.3s ease;
}

.custom-radio,
.switch-item {
  transition: all 0.3s ease;
}

/* 主题色变量 */
:root {
  --primary-color: #0052cc;
  --primary-hover: #003d99;
  --primary-light: #f0f7ff;
  --border-color: #e4e7ed;
  --text-color: #303133;
  --bg-color: #f8f9fa;
}

/* Element Plus 组件样式覆盖 */
:deep(.el-select-dropdown__item.is-selected) {
  color: #0052cc;
  font-weight: 600;
}

:deep(.el-select-dropdown__item:hover) {
  background-color: #f0f7ff;
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #0052cc;
  border-color: #0052cc;
}

:deep(.el-table__body tr.el-table__row--selected > td) {
  background-color: #f0f7ff;
}

:deep(.el-table__body .el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #0052cc;
  border-color: #0052cc;
}
</style>
